package com.wwj.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.wwj.common.constant.ProductConstant;
import com.wwj.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.wwj.gulimall.product.dao.AttrGroupDao;
import com.wwj.gulimall.product.dao.CategoryDao;
import com.wwj.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.wwj.gulimall.product.entity.AttrGroupEntity;
import com.wwj.gulimall.product.service.AttrAttrgroupRelationService;
import com.wwj.gulimall.product.service.AttrGroupService;
import com.wwj.gulimall.product.service.CategoryService;
import com.wwj.gulimall.product.vo.AttrInfoVo;
import com.wwj.gulimall.product.vo.AttrRespVo;
import com.wwj.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wwj.common.utils.PageUtils;
import com.wwj.common.utils.Query;

import com.wwj.gulimall.product.dao.AttrDao;
import com.wwj.gulimall.product.entity.AttrEntity;
import com.wwj.gulimall.product.service.AttrService;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Resource
    private AttrGroupService attrgroupService;

    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Resource
    private CategoryDao categoryDao;

    @Resource
    private AttrGroupDao attrGroupDao;

    @Resource
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttr(AttrVo attr) {
        // 先保存属性的基本信息
        AttrEntity attrEntity = new AttrEntity();
//        attrEntity.setAttrName(attr.getAttrName());
//        attrEntity.setSearchType(attr.getSearchType());
//        attrEntity.setIcon(attr.getIcon());
//        attrEntity.setValueSelect(attr.getValueSelect());
//        attrEntity.setAttrType(attr.getAttrType());
//        attrEntity.setEnable(attr.getEnable());
//        attrEntity.setCatelogId(attr.getCatelogId());
//        attrEntity.setShowDesc(attr.getShowDesc());
//        attrEntity.setValueType(attr.getValueType());
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);
        System.out.println("attrEntity=" + attrEntity);

        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            // 再保存属性-属性分组 关联表信息
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationService.save(relationEntity);
        }
    }

    @Override
    public PageUtils queryPageByCatelogId(Map<String, Object> params, Long catelogId, String attrType) {
        LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<>();

        if (catelogId != null && catelogId > 0){
            wrapper.eq(AttrEntity::getCatelogId, catelogId);
        }

        if (!StringUtils.isEmpty(attrType)){
            wrapper.eq(AttrEntity::getAttrType,"base".equalsIgnoreCase(attrType)?
                    ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        }

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((obj)->{
                obj.eq(AttrEntity::getAttrId, key)
                        .or()
                        .like(AttrEntity::getAttrName, key);
            });
        }


        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> attrRespVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            AttrAttrgroupRelationEntity entity = attrAttrgroupRelationDao.selectOne(
                    new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                            .eq(AttrAttrgroupRelationEntity::getAttrId,
                                    attrRespVo.getAttrId()));
            if (entity != null) {
                Long attrGroupId = entity.getAttrGroupId();
                if (attrGroupId != null) {
                    String groupName = attrGroupDao.selectById(attrGroupId).getAttrGroupName();
                    attrRespVo.setGroupName(groupName);
                }
            }

            if (attrRespVo.getCatelogId() != null) {
                String catelogName = categoryDao.selectById(attrRespVo.getCatelogId()).getName();
                attrRespVo.setCatelogName(catelogName);
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrRespVos);
        return pageUtils;
    }

    @Override
    public AttrInfoVo getAttrInfo(Long attrId) {
        // 先获取到属性的基本信息
        AttrEntity attrEntity = this.getById(attrId);
        AttrInfoVo attrInfoVo = new AttrInfoVo();
        if (attrEntity != null) {
            BeanUtils.copyProperties(attrEntity, attrInfoVo);
            if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
                // 再获取到属性分组id
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(
                        new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                                .eq(AttrAttrgroupRelationEntity::getAttrId
                                        , attrId));
                if (relationEntity != null) {
                    attrInfoVo.setAttrGroupId(relationEntity.getAttrGroupId());
                }
            }
            // 得到分类完整路径
            Long[] catelogPath = categoryService.findCatelogPath(attrEntity.getCatelogId());
            attrInfoVo.setCatelogPath(catelogPath);
        }
        return attrInfoVo;
    }

    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            if (attr.getAttrGroupId() != null) {
                BeanUtils.copyProperties(attr, relationEntity);
                int update = attrAttrgroupRelationDao.update(relationEntity,
                        new LambdaUpdateWrapper<AttrAttrgroupRelationEntity>().
                                eq(AttrAttrgroupRelationEntity::getAttrId,
                                        attr.getAttrId()));
                if (update == 0) {
                    attrAttrgroupRelationDao.insert(relationEntity);
                }
            }
        }
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode()){
            Long attrId = attr.getAttrId();
            LambdaQueryWrapper<AttrAttrgroupRelationEntity> wrapper = new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().
                    eq(AttrAttrgroupRelationEntity::getAttrId, attrId);
            Integer count = attrAttrgroupRelationDao.selectCount(wrapper);
            if (count != 0){
                attrAttrgroupRelationDao.delete(wrapper);
            }
        }
    }

    @Override
    public PageUtils getAttrNoRelation(Map<String, Object> params, Long attrgroupId) {

        LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<>();

        // 排除销售属性
        wrapper.eq(AttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        // 1 查找所属分类id
        Long catelogId = null;
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        if (attrGroupEntity != null) {
            catelogId = attrGroupEntity.getCatelogId();
            if (catelogId != null){
                wrapper.eq(AttrEntity::getCatelogId, catelogId);
            }
        }

        // 2 查找已经关联的属性
        // 2.1 查找当前分类下的所有分组
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.
                selectList(new LambdaQueryWrapper<AttrGroupEntity>().
                        eq(AttrGroupEntity::getCatelogId, catelogId));
        // 2.2 查找这些分组关联的属性
        List<Long> attrIds = null;
        if (attrGroupEntities != null && !attrGroupEntities.isEmpty()) {
            List<Long> groupIds = attrGroupEntities.stream().map((AttrGroupEntity::getAttrGroupId))
                    .collect(Collectors.toList());
            List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationDao.selectList(
                    new LambdaQueryWrapper<AttrAttrgroupRelationEntity>().
                            in(AttrAttrgroupRelationEntity::getAttrGroupId, groupIds));
            if (attrAttrgroupRelationEntities != null && !attrAttrgroupRelationEntities.isEmpty() ){
                attrIds = attrAttrgroupRelationEntities.stream().map((AttrAttrgroupRelationEntity::getAttrId))
                        .collect(Collectors.toList());
            }
        }

        // 2.3 排除这些属性
        if (attrIds != null && !attrIds.isEmpty()) {
            wrapper.notIn(AttrEntity::getAttrId, attrIds);
        }


        // 将检索关键字加入检索条件字
        String key = (String) params.get("key");
        if (key != null && !"".equals(key)){
            wrapper.and((obj)->{
                obj.eq(AttrEntity::getAttrId,key).or()
                        .like(AttrEntity::getAttrName,key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }


}